<?php if ( ! defined('BASEPATH') ) exit('No direct script acces allowed');

	/**
	 * 
	 */
class People_model extends CI_Model {
		
	function __construct() {
		parent::__construct();
	}
	
	function IsAssigned($str, $id){
		$pids = explode(',', $str);
		for ($i=0; $i < sizeof($pids); $i++) { 
			if($id == $pids[$i]) return TRUE;
		}
		return FALSE;
	}
	
	//vrati vsetky cesty ku ktoremu je priradeny clovek 
	function getCestyWherePID($pid){
		$cesty = array(
			'odcesty' => $this->db->get('odcestovani'),
			'pricesty' => $this->db->get('pricestovani')
		);
		$result = array();//bude obsahovat vsetkz cesty ku ktoremu je priradeny clovrk
		//hladame ku ktoremu cestu je priradeny clovek
		foreach ($cesty['odcesty']->result_array() as $key => $obj) {
			if( $this->IsAssigned($obj['person_id'], $pid) ){
				array_push($result, $obj);
			}	
		}
		foreach ($cesty['pricesty']->result_array() as $key => $obj) {
			if( $this->IsAssigned($obj['person_id'], $pid) ){
				array_push($result, $obj);
			}	
		}
		
		return $result; 
		
	}
	
	/*
	 * vyberie jedneho cloveka s prislusnou id
	 */
	function GetPerson($id){
		$result = $this->db->get_where('people', array('person_id' => $id)); //vyberie cloveka kde person_id = id
		return $result->row(); //vrati array informaciami o clovekovi		 
	}
	
	//vrati cloveka podla email
	function checkUnikatnyEmail($email){
		$q = $this->db->where('email', $email)
					  ->get('people');			  
		if( $q->num_rows() > 0 ) return FALSE;
		else return TRUE;
	}
	
	/*
	 * vyberie vsetko z tabulky people
	 */
	function GetAll($limit = 0, $offset = 0){
		if( $limit > 0 ){
			$result = $this->db->order_by("surname", "asc")->get('people', $limit, $offset);
		} else {
			$result = $this->db->order_by("surname", "asc")->get('people');
		}
		return $result->result_array();
	}
	
	
	/*
	 * prida noveho cloveka do tabulky people a vrati jeho id
	 */	
	function AddPerson($data){
		$result = $this->db->insert('people',$data);			
		if( $result ) {
			$res = $this->db->where('email', $data['email'])
						    ->select('person_id')
						    ->get('people');
			return $res->row_array();
		} else {
			return false;
		}
	}
	
	/*
	 * zmeni data o vybranom clovekovi
	 */
	function EditPerson($data){
		$result = $this->db->where('person_id',$data['person_id'])
						   ->limit(1)
				 		   ->update('people',$data);
		
		if( $result ){
			//data boli zmenene
			return TRUE;
		} else {
			//chyba pri query update
			return FALSE;
		}
	}
	
	/*
	 * delete
	 */
	function DeletePerson($id){
		return $this->db->where('person_id',$id)->delete('people');
	}

}	

?>